'use strict'

define(['jquery', 'bootstrap', 'select2', 'validate', 'validate.en', 'shiftform'], function($, validate) {
  return {
    
    init: function(data) {
      
      this.isAllAccomplishConfirmed = data.isAllAccomplishConfirmed;
      
      this.initPage();
      this.submit();
      
    },
    
    initPage: function(){
      
      $(document).find('form').bt_validate();
      
      $(document).on('click','.order-item input[type="checkbox"]', function(e){
          
      	var thId = $(e.currentTarget).attr("id");
      	var tdClass = '.order-'+thId;
      	
        var $item = $(tdClass +' input[name="itemIds"]');
        $item.prop("checked", $(e.currentTarget).is(':checked'));
          
      });
      
      $(document).on('click', '#select-all', function(e) {
        
        var $selectAll = $(e.currentTarget);
        var flag = $selectAll.val();
        var $orderCheckAll = $('.order-item input[type="checkbox"]');
        
        if (flag == 'true') {
          $selectAll.val('false');
          $selectAll.text('取消');
          $orderCheckAll.trigger('click');
        } else {
          $selectAll.val('true');
          $selectAll.text('全选');
          $orderCheckAll.trigger('click');
        }
        
      });
      
    },
    
    submit: function() {
      
      var that = this;
      
      $('form').shiftform({
        beforeSubmit: function() {
          var flag = that.beforeSubmit();
          return flag;
        }
      });
      
    },
    
    
    beforeSubmit: function() {
      
      var that = this;
      
      var $form = $("form"); 
        
      var isChooseOne = false;
      var checkbox = $('input[name = "itemIds"]');
      var quantity = 0;
      for(var i = 0; i < checkbox.length; i++){
        if(checkbox[i].checked){
          isChooseOne = true;
          var text = $('#item-quantity-'+checkbox[i].id).text();
          quantity = quantity + parseInt(text);
        }
      }
      
      if(!isChooseOne){
        
        if (that.isAllAccomplishConfirmed) {
          $('div.invalid-message').html('<h6>提醒&nbsp;:&nbsp;该派车单已全部回单确认，无需再执行此操作</h6>');
        }
        
        $('div.invalid-message').show();
        setTimeout(function() {
          $('div.invalid-message').hide();
        }, 2000);
        return false;
      }
      
      $('input[name="itemQuantity"]').val(quantity);
      return true;
      
    }
              
  }
})

